<?php

namespace app\controller;

use support\Request;

class BaseController
{
    protected function success($data = [])
    {
        return json(['code' => 200, 'msg' => 'success', 'data' => $data], JSON_UNESCAPED_UNICODE);
    }

    protected function error($msg = 'error', $data = [])
    {
        return json(['code' => 500, 'msg' => $msg, 'data' => $data]);
    }

    protected function mergeRequest(Request $request, $isArr = false)
    {
        $params = $request->all();
        $params['x_host_id'] = $request->x_host_id;
        $params['x_shop_user'] = $request->x_shop_user;
        $params['x_host'] = $request->x_host;
        $params['x_payment_host'] = $request->x_payment_host;
        $params['x_lp_link'] = $request->x_lp_link;
        $params['x_template_id'] = $request->x_template_id;
        $params['x_template_type'] = $request->x_template_type;
        $params['x_goods_id'] = $request->x_goods_id;
        $params['x_sign'] = $request->x_sign;
        $params['x_fbclid'] = $request->x_fbclid;
        $params['x_ad_id'] = $request->x_ad_id ?? 0;
        if (isset($request->x_order_id) && !empty($request->x_order_id)) $params['order_id'] = $request->x_order_id;
        if ($isArr) return $params;
        return (object)$params;
    }

    protected function parse_request($request)
    {
        if (is_array($request)) return $request;
        if (is_object($request)) return json_decode(json_encode($request, JSON_UNESCAPED_UNICODE), true);
    }


    protected function xml2arr($xml, $tag)
    {
        $xmlObj = simplexml_load_string($xml);

// 将SimpleXMLElement对象转换为JSON格式的字符串
        $jsonStr = json_encode($xmlObj);

// 将JSON字符串解码为PHP数组
        $array = json_decode($jsonStr, true);
        $data = toOneDimensionalArray($array);
        dd($data);
    }

    protected function toOneDimensionalArray($array)
    {
        $result = [];
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $kk => $vv) {
                    $result[$kk] = $vv;
                }
                $result = array_merge($result, toOneDimensionalArray($value));
            } else {
                $result[$key] = $value;
            }
        }
        return $result;
    }
}
